﻿#include "AlarmHistoryScene.h"

#include <QGraphicsTextItem>
#include <QVariantAnimation>
#include <QGraphicsItemGroup>
#include <QDebug>
#include <QDateTime>

AlarmHistoryScene::AlarmHistoryScene(QObject *parent) : QGraphicsScene(parent)
{
    m_pItemGroup = new QGraphicsItemGroup();

    addItem(m_pItemGroup);
    m_pItemGroup->setPos(0, 0);

    connect(this, &AlarmHistoryScene::sceneRectChanged, this, &AlarmHistoryScene::updateAnimation);
}

void AlarmHistoryScene::addAlarmText(WarningLevel level ,const QString &alarm)
{
    QString detail = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
            .append(QStringLiteral("："))
            .append(alarm);

    QGraphicsTextItem *item = new QGraphicsTextItem(detail);

    QFont font;
    font.setFamily("System");
    font.setPixelSize(12);

    item->setFont(font);
    switch (level)
    {
    case WarningLevel::Normal:
        item->setDefaultTextColor(QColor(227, 207, 87));
        break;
    case WarningLevel::Serious:
        item->setDefaultTextColor(QColor(243, 130, 19));
        break;
    case WarningLevel::Danger:
        item->setDefaultTextColor(QColor("red"));
        break;
    default:
        break;
    }

    int count = m_pItemGroup->childItems().count();

    item->setPos(0, m_pItemGroup->y() + count * (font.pixelSize() + 2));
    m_pItemGroup->addToGroup(item);

    updateAnimation();
}

void AlarmHistoryScene::clear()
{
    if (m_pAnimation)
    {
        m_pAnimation->stop();
        m_pAnimation->deleteLater();
        m_pAnimation = nullptr;
    }

    m_pItemGroup->setPos(0, 0);
    auto list = m_pItemGroup->childItems();
    int count = list.count();
    for (int i = 0; i < count; ++i)
    {
        auto item = list.at(i);
        m_pItemGroup->removeFromGroup(item);
        removeItem(item);
        delete item;
    }
}

void AlarmHistoryScene::updateAnimation()
{
    if (m_pAnimation)
    {
        m_pAnimation->stop();
        m_pAnimation->deleteLater();
        m_pAnimation = nullptr;
    }

    m_pAnimation = new QVariantAnimation(this);
    connect(m_pAnimation, &QVariantAnimation::valueChanged, this, [=](const QVariant &value) {
        m_pItemGroup->setPos(0, value.toDouble());
    });
    m_pAnimation->setLoopCount(-1);

    qreal sceneHeight = this->sceneRect().height();
    m_pItemGroup->setPos(0, sceneHeight);

    m_pAnimation->setDuration((sceneHeight + m_pItemGroup->boundingRect().height()) * 12);
    m_pAnimation->setStartValue(sceneHeight);
    m_pAnimation->setEndValue(-m_pItemGroup->boundingRect().height());
    m_pAnimation->start();
}
